package com.cc.screen;

import com.sun.deploy.util.StringUtils;
import javafx.concurrent.Task;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;

import java.io.File;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * ClassName: RecorderApp
 * Description:
 */
public class RecorderApp extends Application {

    private Recorder recorder = new Recorder(); // 录屏+音频
    private Recorder recorderTemp =  new Recorder(); ;

    @Override
    public void start(Stage primaryStage) throws Exception {
        // 图像窗口

        Alert alert = new Alert(AlertType.WARNING);

        final ImageView[] imageVideo = {new ImageView()};
        imageVideo[0].setFitWidth(800);
        imageVideo[0].setFitHeight(600);
        Boolean[] isRecording = {false};
        AtomicInteger reTime = new AtomicInteger(10);

        AtomicInteger fgTime = new AtomicInteger(10);

        AtomicReference<String> videoPath = new AtomicReference<>("");
        // 状态图标
        Text text = new Text(" 未录制 ");
        text.setTextAlignment(TextAlignment.CENTER);
        text.setWrappingWidth(80);
        text.setX(10);
        text.setY(10);
        final int[] sort = {0};

        TextField textField = new TextField();
        textField.setMaxWidth(100);
        textField.setPromptText("录制间隔时长");
        textField.setText("10");

        textField.textProperty().addListener((obs, oldText, newText) -> {
            if (!newText.matches("\\d*")) {
                textField.setText(oldText);
            }
        });

        Text textTs = new Text("秒");
        textTs.setX(0);
        textTs.setY(1000);
        // 时间
        Label timeLabal = new Label(" 录制时间：");
        timeLabal.setMinWidth(80);
        Text timeText = new Text("00:00:00");
        timeText.setTextAlignment(TextAlignment.CENTER);
        timeText.setWrappingWidth(100);
        GridPane gridPane = new GridPane();
        gridPane.setPrefWidth(80);
        gridPane.setPrefHeight(50);
        gridPane.add(text, 0, 0);
        gridPane.add(timeLabal, 1, 0);
        gridPane.add(timeText, 2, 0);
        gridPane.setAlignment(Pos.CENTER);

        // 开始按钮
        Button startButton = new Button("开始录制");
        startButton.setOnAction(event -> {
            System.out.println("开始录制");
            text.setText("录制中");
            text.setFill(Color.GREEN);
            recorder.setStopped(false);
            try {
                recorder.startRecorder(imageVideo[0], timeText, sort[0]);
                primaryStage.setIconified(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        // 停止按钮
        Button stopButton = new Button("停止录制");
        stopButton.setOnAction(event -> {
            System.out.println("停止录制");
            text.setText("已停止");
            text.setFill(Color.RED);
            isRecording[0]= false;
            recorder.setStopped(true);
            if(recorderTemp!=null){
                recorderTemp.setStopped(true);
            }
        });
        // 选择保存路径按钮
        Button choosePathButton = new Button("选择保存路径");
        choosePathButton.setOnAction(event -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            directoryChooser.setTitle("选择保存路径");
            File selectedDirectory = directoryChooser.showDialog(primaryStage);
            if (selectedDirectory != null) {
                recorder.setRecorderBasePath(selectedDirectory.getAbsolutePath());
                System.out.println("保存路径：" + selectedDirectory.getAbsolutePath());
            }
        });

        // 选择保存路径按钮
        Button chooseVideoButton = new Button("选择视频文件");
        chooseVideoButton.setOnAction(event -> {
            FileChooser directoryChooser = new FileChooser();
            directoryChooser.setTitle("选择视频文件");
            File selectedDirectory = directoryChooser.showOpenDialog(primaryStage);
            if (selectedDirectory != null) {
                videoPath.set(selectedDirectory.getAbsolutePath());
                System.out.println("保存路径：" + videoPath.get());
            }
        });

        // 创建ToggleGroup
        ToggleGroup toggleGroup = new ToggleGroup();
        RadioButton radioButton1 = new RadioButton("按秒批量分割");
        RadioButton radioButton2 = new RadioButton("自定义分割");

        radioButton1.setToggleGroup(toggleGroup);
        radioButton2.setToggleGroup(toggleGroup);



        TextField secondTextField = new TextField();
        secondTextField.setMaxWidth(100);
        secondTextField.setPromptText("分割时长单位秒");

        TextField startSecondTextField = new TextField();
        startSecondTextField.setMaxWidth(100);
        startSecondTextField.setPromptText("00:00:00");
        startSecondTextField.setVisible(false);
        startSecondTextField.setManaged(false);

        TextField startSecondText = new TextField();
        startSecondText.setMaxWidth(100);
        startSecondText.setPromptText("分割时长单位秒");
        startSecondText.setVisible(false);
        startSecondText.setManaged(false);
//        secondTextField.setText();

        secondTextField.textProperty().addListener((obs, oldText, newText) -> {
            if (!newText.matches("\\d*")) {
                secondTextField.setText(oldText);
            }
        });

        // 监听选中状态
        radioButton1.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {

                secondTextField.setVisible(true);
                secondTextField.setManaged(true);
                startSecondTextField.setVisible(false);
                startSecondTextField.setManaged(false);
                startSecondText.setVisible(false);
                startSecondText.setManaged(false);

                System.out.println("选项1被选中");
            } else {
                secondTextField.setVisible(false);
                secondTextField.setManaged(false);
                System.out.println("选项1未被选中");
                startSecondTextField.setVisible(true);
                startSecondTextField.setManaged(true);
                startSecondText.setVisible(true);
                startSecondText.setManaged(true);
            }
        });

        radioButton2.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                secondTextField.setVisible(false);
                secondTextField.setManaged(false);
                System.out.println("选项2未被选中");
                startSecondTextField.setVisible(true);
                startSecondTextField.setManaged(true);
                startSecondText.setVisible(true);
                startSecondText.setManaged(true);

            } else {

                secondTextField.setVisible(true);
                secondTextField.setManaged(true);
                startSecondTextField.setVisible(false);
                startSecondTextField.setManaged(false);
                startSecondText.setVisible(false);
                startSecondText.setManaged(false);

                System.out.println("选项2被选中");
            }
        });

        // 停止按钮
        Button fgButton = new Button("视频分割");
        fgButton.setOnAction(event -> {
            if(startSecondTextField.getText()!=null && !"".equals(startSecondTextField.getText())) {
                String startTime = startSecondTextField.getText();
                String regex = "^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$";
                if(!startTime.matches(regex)){
                    alert.setTitle("信息提示");
                    alert.setContentText("开始时间格式不正确");
                    alert.showAndWait();
                    return;
                }

                FFmpegSegmenter fFmpegSegmenter =new FFmpegSegmenter(videoPath.get(),recorder.getRecorderBasePath()+"\\"+new Date().getTime()+"%03d.mp4",fgTime.get(),null);
                fFmpegSegmenter.segment();
                alert.setTitle("信息提示");
                alert.setContentText("分割成功！");
                alert.showAndWait();
            }

            if(secondTextField.getText()!=null && !"".equals(secondTextField.getText())) {
                fgTime.set(Integer.parseInt(secondTextField.getText()));
                if (fgTime.get() < 1) {
                    alert.setTitle("信息提示");
//                alert.setHeaderText("这是一个信息提示框");
                    alert.setContentText("视频分割时间不行大于0");
                    alert.showAndWait();
                    return;
                }
                if(videoPath.get()==null || "".equals(videoPath.get())){
                    alert.setTitle("信息提示");
                    alert.setContentText("请选择分割文件");
                    alert.showAndWait();
                    return;
                }
                FFmpegSegmenter fFmpegSegmenter =new FFmpegSegmenter(videoPath.get(),recorder.getRecorderBasePath()+"\\"+new Date().getTime()+"%03d.mp4",fgTime.get(),null);
                fFmpegSegmenter.segment();
                alert.setTitle("信息提示");
                alert.setContentText("分割成功！");
                alert.showAndWait();
//                VideoUtils.splitVideo(videoPath.get(), recorder.getRecorderBasePath()+"\\"+new Date().getTime()+".mp4", fgTime.get(), 1);
            }
        });

        // 停止按钮
        Button startOverButton = new Button("开始间隔录制");
        startOverButton.setOnAction(event -> {

            text.setText("间隔录制开始");
            text.setFill(Color.RED);
            reTime.set(Integer.parseInt(textField.getText()));
            if(reTime.get()<1){
                text.setText("间隔大于0");
                return;
            }
            if(isRecording[0]){
                text.setText("录制中");
                text.setFill(Color.GREEN);
                recorder.setStopped(false);
                return;
            }else{
                isRecording[0]=true;
            }

            primaryStage.setIconified(true);

            Task<Void> task = new Task<Void>() {
                @Override
                protected Void  call() throws Exception {
                    try {
                        int timeLong = 0;
                        int filesCount = 0;
                        while (isRecording[0]) {
                            try {
                                filesCount++;
                                text.setText("共录制"+filesCount+"文件");

                                imageVideo[0] = new ImageView();
                                imageVideo[0].setFitWidth(800);
                                imageVideo[0].setFitHeight(600);
                                Recorder recorderTemp = new Recorder();
                                sort[0] = sort[0] + 1;
                                recorderTemp.setRecorderBasePath(recorder.getRecorderBasePath());
                                recorderTemp.startRecorder(imageVideo[0], timeText, sort[0]);

                                timeLong = timeLong + reTime.get() * 1000;
                                Thread.sleep(reTime.get() * 1000L);
                                recorderTemp.setStopped(true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }

            };
            new Thread(task).start();
        });



        // 水平盒子
        HBox hBox = new HBox();
        hBox.getChildren().addAll(gridPane, textField,textTs,startButton,startOverButton,stopButton, choosePathButton);
        hBox.setSpacing(15);
        hBox.setPadding(new Insets(30, 12, 15, 12));
        hBox.setStyle("-fx-background-color: #f0f0f0;");


        HBox hBox2 = new HBox();
        hBox2.getChildren().addAll(secondTextField,startSecondTextField,startSecondText,radioButton1,radioButton2,chooseVideoButton,fgButton);
        hBox2.setSpacing(15);
        hBox2.setPadding(new Insets(0, 12, 15, 12));
        hBox2.setStyle("-fx-background-color: #f0f0f0;");

        // 垂直盒子
        VBox vbox = new VBox(hBox,hBox2);

        vbox.setSpacing(0);
        vbox.setBackground(Background.EMPTY);
        vbox.getChildren().addAll(imageVideo[0]);
        // 场景
        Scene scene = new Scene(vbox,Color.BLACK);
        //设置应用大小并show
        primaryStage.setTitle("菜菜录屏");
        primaryStage.setScene(scene);
        primaryStage.setWidth(800);
        primaryStage.setHeight(600);
        primaryStage.setResizable(false);
        primaryStage.show();

        //关闭请求
        primaryStage.setOnCloseRequest(event -> {
            System.out.println("关闭请求");
            recorder.setStopped(true);
        });
    }

//
//    public static void main(String[] args) {
//
//        String videoPath ="file:\\E:\\video\\20241125_141851_3.mp4"; // 在线视频的地址
//
//        VideoCapture videoCapture = new VideoCapture(videoPath);
//        boolean opened = videoCapture.isOpened();
//        if (!opened) {
//            throw new RuntimeException("无法解析视频文件");
//        }
//        Mat frame = new Mat();
//        int count = 0;
//        while (true) {
//            boolean read = videoCapture.read(frame);
//            if (!read || frame.empty()) {
//                break;
//            }
//            Imgcodecs.imwrite("D:\\avideoPic\\yaoyaolingxian\\" + count + ".jpg", frame); // 逐帧保存图片
//            System.out.println("已经保存了第"+ ++count + "帧 照片");
//
//        }
//        videoCapture.release();
//        frame.release();
//
//    }

    public static void main(String[] args) throws Exception {
        launch(args);
    }
}
